/**
 * 
 */
package uy.com.pzit.fpmundialmodel.dao;

import java.util.List;

import net.sf.ehcache.ObjectExistsException;

import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.type.Type;

import uy.com.pzit.fpmundialmodel.dao.dbObjects.DBObject;
import uy.com.pzit.fpmundialmodel.dao.dbObjects.DBTemplate;
import uy.com.pzit.fpmundialmodel.domain.Fase;
import uy.com.pzit.fpmundialmodel.domain.PaisEnCompeticion;

/**
 * @author pferraz
 *
 */
public class PaisEnCompeticionDAO {
	
	private static Logger logger=Logger.getLogger(PaisEnCompeticionDAO.class);
	
	public PaisEnCompeticion addPais(PaisEnCompeticion pais) {
		return (DBObject.addObject(pais))?pais:null;
	}

	@SuppressWarnings("unchecked")
	public List<PaisEnCompeticion> getPaisEnCompByMundialAndFase(int idComp,Fase fase) {
		Session sess = null;
		List<PaisEnCompeticion> result = null;
		try {
			sess = DBTemplate.getConnTemplate().getSessionFactory().openSession();
			Query query = sess.createQuery("select c.paises from uy.com.pzit.fpmundialmodel.domain."+((fase==Fase.ELIMINATORIA)?"Eliminatoria":"Grupo")+" c where c.id=?");
			query.setParameters(new Object[] {idComp},new Type[]{Hibernate.INTEGER});
			result = query.list();
			if (result.isEmpty()) {
				throw new ObjectExistsException("No existen paises en competicion.");
			}
		} catch (HibernateException e) {
			logger.error("Error al buscar paises", e);
		} finally {
			if (sess != null) {
				sess.close();
			}

		}
		return result;
	}

	public PaisEnCompeticion updatePaisEnComp(PaisEnCompeticion p) {
		
		return (DBObject.updateObject(p))?p:null;
	}

}
